/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2024-01-15 11:35:44
 * @LastEditTime : 2024-01-15 12:19:36
 */
import { Provide } from '@midwayjs/decorator';
import * as fs from 'fs-extra';
import * as path from 'path';
import * as archiver from 'archiver';

@Provide()
export class ZipService {
  async createAndSendZip(sourceDir: string, res: any, name: string) {
    const outputName = name || 'datav.zip';
    const archive = archiver('zip', { zlib: { level: 9 } });

    // 设置输出到 HTTP 响应流
    archive.pipe(res);
    // 设置响应头
    res.setHeader('Content-Type', 'application/zip');
    res.setHeader('Content-Disposition', `attachment; filename=${outputName}`);

    try {
      await archive.directory(sourceDir, false);
      archive.finalize();
    } catch (err) {
      console.error('Archiving error:', err);
      res
        .status(500)
        .send({ error: 'An error occurred while creating the ZIP file.' });
      return;
    }

    // 监听归档完成事件和错误事件
    archive.on('finish', () => {
      console.log(`Archive wrote ${archive.pointer()} total bytes.`);
      res.end();
    });

    archive.on('error', err => {
      console.error('Archiver error:', err);
      res.status(500).send({ error: 'Failed to create the ZIP file.' });
    });
  }
}
